package demo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-10-20
 * Time: 23:03
 */

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 自己实现一个阻塞队列，实现生产者消费者模型
 */

class MyBlockingQueue{

    private String[] data = null;

    private int head = 0;//队首
    private int tail = 0;//队尾
    private int size = 0;//元素个数

    MyBlockingQueue(int capacity){
        data = new String[capacity];
    }

    //入队列
    public void put(String elem) throws InterruptedException {
        synchronized (this) {
            while (size >= data.length) {
                //阻塞
                this.wait();//队列不满时唤醒,其他线程take
            }
            data[tail] = elem;

//        tail = (tail+1) % data.length;

            tail++;
            if (size >= data.length) {
                tail = 0;
            }

            size++;
            this.notify();
        }

    }

    public String take() throws InterruptedException {

        synchronized (this) {
            while (size == 0) {
                //阻塞
                this.wait();//队列不空时唤醒,其他线程put
            }
            String ret = data[head];
            head++;
            if (size >= data.length) {
                head = 0;
            }

//        head = (head+1) % data.length;

            size--;
            this.notify();
            return ret;
        }
    }

}

public class Demo3 {
    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(100);

        Thread producer = new Thread(()->{
            int n = 0;
            while (true){
                try {
                    queue.put(n + "");
                    System.out.println("生产元素 " + n);
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                n++;
            }
        },"producer ");


        Thread consumer = new Thread(()->{

            while (true){
                try {
                    String n = queue.take();
                    System.out.println("消费元素 " + n);
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"consumer ");


        producer.start();
        consumer.start();
    }
}
